package top.lidee.common.service.twice.popularize.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.transaction.annotation.Transactional;
import top.lidee.common.dto.AccountInfo;
import top.lidee.common.enums.StatusEnum;
import top.lidee.common.service.twice.management.BmsManagerService;
import top.lidee.common.service.twice.popularize.PtpBeesInfoService;
import top.lidee.common.util.CommonUtil;
import top.lidee.framework.enums.CommonExceptionEnum;
import top.lidee.framework.result.GlobalCheck;
import top.lidee.framework.result.PageUtils;
import top.lidee.framework.result.ResponseResult;
import top.lidee.module.backendApi.twice.page.Query;
import top.lidee.repository.mapper.twice.popularize.PtpBeesInfoMapper;
import top.lidee.repository.model.twice.pojo.management.BmsManagerEntity;
import top.lidee.repository.model.twice.pojo.popularize.PtpBeesInfoEntity;
import top.lidee.repository.model.twice.vo.management.ManagerVo;
import top.lidee.repository.model.twice.vo.popularize.PtpBeesInfoSaveVo;
import top.lidee.repository.model.twice.vo.popularize.PtpBeesInfoUpdateVo;
import top.lidee.repository.model.twice.vo.popularize.PtpBeesInfoVo;
import top.lidee.utils.CopyBean;
import top.lidee.utils.MyCollUtil;

import static top.lidee.framework.constant.ManagerStatus.ADMIN;
import static top.lidee.utils.MapParamsUtil.getKey;
import static top.lidee.utils.MapParamsUtil.getStatus;


@Service("ptpBeesInfoService")
public class PtpBeesInfoServiceImpl extends ServiceImpl<PtpBeesInfoMapper, PtpBeesInfoEntity> implements PtpBeesInfoService {

    @Autowired
    private BmsManagerService bmsManagerService;

    /**
     * @param params
     * @return java.util.List<top.lidee.repository.model.twice.pojo.popularize.PtpBeesInfoEntity>
     * @description 根据条件查询小蜜蜂
     * @author zhangyiheng
     * @date 2024/9/23 16:21
     */
    @Override
    public List<PtpBeesInfoEntity> queryBeesInfoByParams(Map<String, Object> params) {
        String status = (String) params.get("status");
        Integer beesId = (Integer) params.get("beesId");


        List<PtpBeesInfoEntity> list = this.list(Wrappers.<PtpBeesInfoEntity>lambdaQuery()
                .eq(!Objects.isNull(beesId), PtpBeesInfoEntity::getBeesId, beesId)
                .eq(StrUtil.isNotBlank(status), PtpBeesInfoEntity::getStatus, status));


        return list;
    }

    /**
     * @param params
     * @param accountInfo
     * @return top.lidee.framework.result.PageUtils
     * @description 推广人/小蜜蜂人员表-条件查询
     * @author zhangyiheng
     * @date 2024/9/24 16:58
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, AccountInfo accountInfo) {

        //手机号、昵称
        String status = getStatus(params);
        String nickname= (String) params.get("nickname");
        String phone= (String) params.get("phone");
        String managerName= (String) params.get("managerName");
        String province= (String) params.get("province");
        String city= (String) params.get("city");
        String county= (String) params.get("county");
        Integer mId = null;
        if(StrUtil.isNotBlank(managerName)){
            mId = bmsManagerService.getIdByName(managerName);
        }
        LambdaQueryWrapper<PtpBeesInfoEntity> wrapper = Wrappers.<PtpBeesInfoEntity>lambdaQuery()
                .like(StrUtil.isNotBlank(nickname), PtpBeesInfoEntity::getNickname, nickname)
                .eq(StrUtil.isNotBlank(phone), PtpBeesInfoEntity::getPhone, phone)
                .eq(mId!=null, PtpBeesInfoEntity::getManagerId, mId)
                .eq(StrUtil.isNotBlank(province), PtpBeesInfoEntity::getProvince, province)
                .eq(StrUtil.isNotBlank(city), PtpBeesInfoEntity::getCity, city)
                .eq(StrUtil.isNotBlank(county), PtpBeesInfoEntity::getCounty, county);


        if (!Objects.isNull(status)) {
            if (Objects.equals(status, StatusEnum.ENABLED.getKey())) {
                wrapper.and(wq -> wq.eq(PtpBeesInfoEntity::getStatus, StatusEnum.ENABLED.getKey()));
            } else {
                wrapper.and(wq -> wq.eq(PtpBeesInfoEntity::getStatus, StatusEnum.FORBIDDEN.getKey()));
            }
        }

        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());
        //admin查询所有
        if (!Objects.equals(managerId, 1)) {
            wrapper.eq(PtpBeesInfoEntity::getManagerId, managerId);
        }
        IPage<PtpBeesInfoEntity> page = this.page(
                new Query<PtpBeesInfoEntity>().getPage(params),
                wrapper
        );

        List<PtpBeesInfoEntity> records = page.getRecords();

        List<PtpBeesInfoVo> ptpBeesInfoVos;
        if (MyCollUtil.isNotEmpty(records)) {
            //设置代理人
            if (!Objects.equals(managerId, 1)) {
                ptpBeesInfoVos = CopyBean.copyBeanList(records, PtpBeesInfoVo.class);
                ptpBeesInfoVos.forEach(po -> po.setManagerName(accountInfo.getManagerName()));
            } else {
                ptpBeesInfoVos = records.stream().map(po -> {
                    PtpBeesInfoVo vo = CopyBean.copyBean(po, PtpBeesInfoVo.class);
                    BmsManagerEntity byId = bmsManagerService.getById(po.getManagerId());
                    if(byId != null){
                        vo.setManagerName(byId.getName());
                    }
                    return vo;
                }).collect(Collectors.toList());
            }
            IPage<PtpBeesInfoVo> pageVo = new Page<>();
            pageVo.setTotal(page.getTotal());
            pageVo.setRecords(ptpBeesInfoVos);
            pageVo.setPages(page.getPages());
            pageVo.setSize(page.getSize());
            pageVo.setCurrent(page.getCurrent());

            return new PageUtils(pageVo);
        }
        return null;
    }

    /**
     * @param vo
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 推广人/小蜜蜂人员表-新增
     * @author zhangyiheng
     * @date 2024/9/24 17:27
     */
    @Override
    @Transactional
    public ResponseResult saveBees(PtpBeesInfoSaveVo vo, AccountInfo accountInfo) {

        //校验是否为服务商或公司管理员
            Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        PtpBeesInfoEntity beesInfo = CopyBean.copyBean(vo, PtpBeesInfoEntity.class);
        //如果没有代理商id默认代理商是admin
        if (Objects.isNull(vo.getManagerId())) {
            beesInfo.setManagerId(ADMIN);
        } else {
            beesInfo.setManagerId(managerId);
        }
        beesInfo.setInvitationCode(CommonUtil.getInvitationCode());
        beesInfo.setCreateTime(new Date());
        beesInfo.setUpdateTime(new Date());
        this.save(beesInfo);
        return ResponseResult.ok();
    }

    /**
     * @param beesId
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 推广人/小蜜蜂人员表-根据id查询
     * @author zhangyiheng
     * @date 2024/9/24 17:35
     */
    @Override
    public ResponseResult getBeesById(Integer beesId, AccountInfo accountInfo) {
        //校验是否为服务商或公司管理员
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        PtpBeesInfoEntity beesInfo = this.getById(beesId);
        PtpBeesInfoVo beesInfoVo = CopyBean.copyBean(beesInfo, PtpBeesInfoVo.class);

        String name = bmsManagerService.getById(beesInfo.getManagerId()).getName();
        beesInfoVo.setManagerName(name);

        return ResponseResult.okResult(beesInfoVo);
    }


    /**
     * @param vo
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 推广人/小蜜蜂人员表-修改
     * @author zhangyiheng
     * @date 2024/9/24 17:40
     */
    @Override
    @Transactional
    public ResponseResult updateInfo(PtpBeesInfoUpdateVo vo, AccountInfo accountInfo) {
        //校验是否为服务商或公司管理员
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        //确定上下级管理
        PtpBeesInfoEntity beesInfo = this.getById(vo.getId());
        if (!Objects.equals(managerId, ADMIN)) {
            if (!Objects.equals(beesInfo.getManagerId(), managerId)) {
                return ResponseResult.errorResult(CommonExceptionEnum.NOT_PERMISSION);
            }
        }

        //修改
        PtpBeesInfoEntity copied = CopyBean.copyBean(vo, PtpBeesInfoEntity.class);
        this.update(copied, Wrappers.<PtpBeesInfoEntity>lambdaUpdate()
                .eq(PtpBeesInfoEntity::getBeesId, vo.getId())
        );

        return ResponseResult.ok();
    }


    /**
     * @param beesId
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 推广人/小蜜蜂人员表-修改状态
     * @author zhangyiheng
     * @date 2024/9/24 17:45
     */
    @Override
    @Transactional
    public ResponseResult updateStatusById(Integer beesId, AccountInfo accountInfo) {
        //校验是否为服务商或公司管理员
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        //确定上下级管理
        PtpBeesInfoEntity beesInfo = this.getById(beesId);
        if (!Objects.equals(managerId, ADMIN)) {
            if (!Objects.equals(beesInfo.getManagerId(), managerId)) {
                return ResponseResult.errorResult(CommonExceptionEnum.NOT_PERMISSION);
            }
        }

        //判断状态
        String status = "";
        if (Objects.equals(beesInfo.getStatus(), StatusEnum.ENABLED.getKey())) {
            status = StatusEnum.FORBIDDEN.getKey();
        } else {
            status = StatusEnum.ENABLED.getKey();
        }

        //修改
        this.update(Wrappers.<PtpBeesInfoEntity>lambdaUpdate()
                .set(PtpBeesInfoEntity::getStatus, status)
                .eq(PtpBeesInfoEntity::getBeesId, beesId));

        return ResponseResult.ok();
    }

    /**
     * @param beesIds
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 推广人/小蜜蜂人员表-删除小蜜蜂
     * @author zhangyiheng
     * @date 2024/9/24 17:49
     */
    @Override
    @Transactional
    public ResponseResult deleteByIds(Integer[] beesIds, AccountInfo accountInfo) {
        //校验是否为服务商或公司管理员
        Integer managerId = GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());

        if (!Objects.isNull(beesIds)) {
            for (Integer beesId : beesIds) {
                //确定上下级关系
                PtpBeesInfoEntity beesInfo = this.getById(beesId);
                if (!Objects.equals(managerId, ADMIN)) {
                    if (!Objects.equals(beesInfo.getManagerId(), managerId)) {
                        return ResponseResult.errorResult(CommonExceptionEnum.NOT_PERMISSION);
                    }
                }

                //判断状态
                if (Objects.equals(beesInfo.getStatus(), StatusEnum.ENABLED.getKey())) {
                    return ResponseResult.errorResult(CommonExceptionEnum.XMFSQYYZT_BNSC);
                }

            }
            //删除
            this.removeByIds(Arrays.asList(beesIds));

            //修改上级小蜜蜂数量
            if (Objects.equals(managerId, ADMIN)) {

                List<PtpBeesInfoEntity> list = this.list(Wrappers.<PtpBeesInfoEntity>lambdaQuery()
                        .in(PtpBeesInfoEntity::getManagerId, Arrays.asList(beesIds)));

                Map<Integer, List<PtpBeesInfoEntity>> map = list.stream().collect(Collectors.groupingBy(PtpBeesInfoEntity::getManagerId));

                for (Map.Entry<Integer, List<PtpBeesInfoEntity>> entry : map.entrySet()) {
                    bmsManagerService.update(Wrappers.<BmsManagerEntity>lambdaUpdate()
                            .eq(BmsManagerEntity::getManagerId, entry.getKey())
                            .setSql("total_bees = total_bees - " + entry.getValue().size() + 1));
                }


            }else {
                bmsManagerService.update(Wrappers.<BmsManagerEntity>lambdaUpdate()
                        .eq(BmsManagerEntity::getManagerId, managerId)
                        .setSql("total_bees = total_bees - " + Arrays.asList(beesIds).size() + 1));
            }

            return ResponseResult.ok();
        }
        return null;
    }
}